import json

from apps.user.models import StudentClass
from utils import restful
from .models import *
from .serializers import AdditionalSerializer, RankSerializer, ScholarshipSerializer, SubmitRecordsSerializer


# 获取附加分等级
def get_rank_list(request):
    ranks = Rank.objects.all()
    data = RankSerializer(ranks, many=True).data

    return restful.ok(data=data)


# 根据类型id获取附加分
def get_score_list(request):
    type = request.GET.get('type_id')
    scholarship_id = request.GET.get('scholarship_id', 1)
    scores = Additional.objects.filter(type__id=type, scholarship_id_id=scholarship_id)
    data = AdditionalSerializer(scores, many=True).data

    return restful.ok(data=data)


# 提交奖学金申请
def submit_application(request):
    data = json.loads(request.POST.get('data'))
    semester = request.POST.get('semester', '')
    other = request.POST.get('other', '')
    scholarship_id = request.POST.get('scholarship_id', '')
    user_id = request.POST.get('user_id')
    grade_sql_data = []
    course_results = 0  # 课程成绩 = 考试成绩 * 学分 / 总学分
    character_result = 60  # 品德成绩
    study_result = 60  # 学业成绩
    style_result = 60  # 问题成绩
    total_credits = 0  # 总学分

    for type in data:
        if type == 'grade_list':
            grade_list = data[type]
            for grade in grade_list:
                if grade['nature'] != '06':
                    total_credits += float(grade['credit'])
    for type in data:
        all_nature = 0
        # 处理课程成绩，将表格数据生成sql语句
        if type == 'grade_list':
            grade_list = data[type]
            for grade in grade_list:
                if grade['nature'] != '06':
                    course_results += float(grade['grade']) * float(grade['credit']) / total_credits
                grade_sql = Grade(nature=grade['nature'], course_name=grade['course_name'],
                                  grade=grade['grade'], credit=grade['credit'], user_id_id=user_id)
                grade_sql_data.append(grade_sql)
        # 处理附加分选项，并计算总分数
        if len(data[type]) > 0:
            for additional in data[type]:
                if additional['nature'] == '加分':
                    if 'num' in additional:
                        all_nature += float(additional['fraction']) * float(additional['num'])
                    else:
                        all_nature += float(additional['fraction'])
                if additional['nature'] == '扣分':
                    if 'num' in additional:
                        all_nature -= float(additional['fraction']) * float(additional['num'])
                    else:
                        all_nature -= float(additional['fraction'])
        if type == 'character':
            character_result += all_nature
        if type == 'study':
            study_result += all_nature
        if type == 'style':
            style_result += all_nature
    Grade.objects.bulk_create(grade_sql_data)  # 将数据插入成绩表
    total_score = course_results * 0.7 + (character_result + study_result + style_result) * 0.1
    SubmitRecords.objects.create(user_id_id=user_id, character=data['character'], study=data['study'],
                                 style=data['style'], grade=data['grade_list'], semester=semester, other=other,
                                 character_result=character_result, study_result=study_result,
                                 style_result=style_result, course_results=course_results * 0.7,
                                 total_score=total_score)

    return restful.ok(message="提交成功")


# 根据奖学金名称id，获取所有附加分
def get_scholarship_info(request):
    id = request.GET.get('id')
    scholarship = Scholarship.objects.filter(id=id)
    data = ScholarshipSerializer(scholarship, many=True).data

    return restful.ok(data=data)


# 获取用户奖学金申请信息
def get_user_submit_records(request):
    user_id = request.GET.get("user_id")
    semester = request.GET.get("semester", '')
    if semester:
        result = SubmitRecords.objects.filter(user_id_id=user_id, semester=semester)
    else:
        result = SubmitRecords.objects.filter(user_id_id=user_id)

    return restful.ok(data=list(result.values()))


# 获取辅导员带领班级
def get_instructor_class(request):
    instructor_id = request.GET.get('instructor_id')
    result = StudentClass.objects.filter(instructor_id__id=instructor_id)

    return restful.ok(data=list(result.values()))


# 辅导员查看所有学生的综合成绩
def get_all_student_records(request):
    class_id = request.GET.get('class_id')
    scholarship_id = request.GET.get('scholarship_id')
    semester = request.GET.get('semester')
    all_data = SubmitRecords.objects.filter(user_id__userinfo__student_class_id=class_id, scholarship_id=scholarship_id,
                                            semester=semester)
    # -order_by表示从大到小进行排序
    result = SubmitRecordsSerializer(all_data.order_by('-total_score'), many=True).data

    return restful.ok(data=result)


def get_all_scholarship(request):
    result = Scholarship.objects.all()

    return restful.ok(data=list(result.values()))
